package com.test;

import com.test.demo01.TestApplicationContextInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@SpringBootApplication
@EnableScheduling
public class AdvanceApplication {

    /**
     * 日志输出器.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(AdvanceApplication.class);
    /**
     * 默認预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了.
     */
    private static final long CROSS_MAX_AGE = 180000000L;

    /**
     * 表示所有的通配符.
     */
    private static final String ALL_WILDCARD = "*";

    public static void main(String[] args) {
        try {
            SpringApplication sa = new SpringApplication(AdvanceApplication.class);
            sa.addInitializers(new TestApplicationContextInitializer());
            sa.run(args);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("boot up fail :", e);
        }
    }

    /**
     * 跨域請求設置.
     * @return 註冊過濾器
     */
    @Bean
    public FilterRegistrationBean corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        // 允许cookies跨域
        config.setAllowCredentials(Boolean.TRUE);
        // #允许访问的头信息,*表示全部
        config.addAllowedHeader(ALL_WILDCARD);
        // #允许向该服务器提交请求的URI，*表示全部允许，在SpringMVC中，如果设成*，会自动转成当前请求头中的Origin
        config.addAllowedOriginPattern(ALL_WILDCARD);
        // 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
        config.setMaxAge(CROSS_MAX_AGE);
        // 允许提交请求的方法，*表示全部允许
        config.addAllowedMethod(ALL_WILDCARD);
        //暴露哪些头部信息
        config.addExposedHeader(ALL_WILDCARD);
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}
